{% extends '__base_local__.html' %}

{% block title %}粘贴板{% endblock %}
{% block beforehead %}
<!-- <script src="https://unpkg.com/vue@next"></script> -->
<script src="static/vue.global.js.js"></script>
{% endblock %}
{% block content %}
<!-- Content Header (Page header) -->

<section class="content-header">
    <h1>
        粘贴板
        <small>共享粘贴板信息</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">粘贴板</li>
    </ol>
</section>
<div>
    <!-- <span style="color: rgb(33, 37, 41); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'Liberation Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(248, 249, 250); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">用户未登录</span> -->
</div>

<div class="container" id="main">
    <div class="row">
        <div class="col-md-8 pb-4">
            <textarea id="paste" style="width: 100%" rows="3" placeholder="paste conten here"></textarea>
        </div>
        <aside class="col-md-4 blog-sidebar">
            <div class="p-4 mb-3 bg-light rounded">
                <h4 class="font-italic">用户信息</h4>
                {% if __user__ %}
                <p class="mb-0">{{ __user__.name }}</p>
                <p class="mb-0">{{ __user__.email }}</p>
                {% else %}
                <p class="mb-0">用户未登录</p>
                {% endif %}
            </div>
        </aside>
    </div>
    <div class="row">
        <div class="col">
            <h1>Index</h1>
        </div>
    </div>
</div>

</div>
{% endblock %}

{% block beforebody %}
<script src="static/vue/vue.global-3.2.31.js"></script>
<script src="static/vue/vuex.global-4.0.2.js"></script>
<script src="static/vue/vue-router.global-4.0.14.js"></script>
<script src="static/vue/vue3-sfc-loader-5.3.5.js"></script>
<script src="static/main.js"></script>
<script>
    let clipboard = {
        // data返回值是暴露的属性
        data() {
            return {
                items: [],
                vue_export: {
                    show: false,
                    content: ''
                },
                vue_import: {
                    show: false,
                    content: ''
                },
                vue_clipview: {
                    show: false,
                },
                loading: false,
                pageIndex: 1,
                pages: 1,
                paged: false,
                searchKey: '',
            }
        },
        props: ['index'],
        components: {
            'loading': component('static/vue/loading.vue'),
            'export': component('static/vue/export.vue'),
            'import': component('static/vue/import.vue'),
            'clipview': component('static/clipboard/clipview.vue'),
        },
        delimiters: ['+{', '}'],
        template: `
            <div class="row">
                <div class="col-md-8 pb-4">
                    <textarea @paste="onPaste($event)" style="width: 100%;resize:none;" rows="3" placeholder="paste conten here"></textarea>
                    <span class="input-group p-0">
                        <input type="text" class="form-control" @keyup.enter="loadItems(1)" v-model="searchKey" placeholder="搜索" aria-label="搜索" aria-describedby="button-search">
                        <button class="btn btn-outline-secondary" type="button" id="button-search" @click="loadItems(1)"><i class="fa fa-search"></i></button>
                    </span>

                </div>
                <aside class="col-md-4 blog-sidebar">
                    <div class="p-4 mb-3 bg-light rounded">
                        <h4 class="font-italic">
                            <span>用户信息</span>
                            <small class="float-right" style="cursor: pointer">
                                <a class="pr-3" @click="exportAll" data-toggle="tooltip" data-placement="top" title="导出"><i class="fa fa-share-square-o"></i></a>
                                <a class="pr-3" @click="importClip" data-toggle="tooltip" data-placement="top" title="导入"><i class="fa fa-upload"></i></a>
                            </small>
                        </h4>
                        {% if __user__ %}
                        <p class="mb-0">{{ __user__.name }}</p>
                        <p class="mb-0">{{ __user__.email }}</p>
                        {% else %}
                        <p class="mb-0">用户未登录</p>
                        {% endif %}
                    </div>
                </aside>
            </div>
            <div class="row" >
                <div v-for="item in items" class="col-sm-12 col-md-4 pb-4 pt-4 border rounded">
                    <div class="card" style="cursor: pointer">
                        <a @click="deleteItem(item)" class="position-absolute" style="right: 5px;cursor: pointer"><i class="fa fa-trash-o"></i></a>
                        <a @click="viewdoc(item)" class="position-absolute" style="right: 25px;cursor: pointer"><i class="fa fa-file-code-o"></i></a>
                        <a @click="viewimg(item)" class="position-absolute" style="right: 45px;cursor: pointer"><i class="fa fa-file-image-o"></i></a>
                        <a @click="exportOne(item)" class="position-absolute" style="right: 65px;cursor: pointer"><i class="fa fa-share-square-o"></i></a>
                        <img v-if="item.type && item.type.startsWith('image')" class="card-body" :src="item.content" alt="...">
                        <textarea v-else @click="copyContent($event)" class="card-body" rows="10" readOnly style="height: 100%;width: 100%;resize:none;" :value="item.content"></textarea>
                    </div>
                </div>
            </div>
            <export :show='vue_export.show' :content='vue_export.content' @hide="vue_export.show=false"></export>
            <import :show='vue_import.show' :content='vue_import.content' @hide="vue_import.show=false" @save="onImportClip"></import>
            <clipview :show='vue_clipview.show' :content='vue_clipview.content' @hide="vue_clipview.show=false">
                <div class="clipview" style="background: #FFF;max-width: 95vw;"></div>
            </clipview>
            <transition>
                <loading v-if="loading"></loading>
            </transition>
            `,
        mounted() {
            this.loadItems()
            window.addEventListener('scroll', (event)=>{
                event.preventDefault()
                if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
                    // 滚动条已经到达底部
                    console.log('滚动条已到达底部');
                    !this.paged && this.pageIndex < this.pages && this.loadItems(this.pageIndex + 1)
                }
            })
        },
        watch: {
        },
        updated() {
        },
        methods: {
            loadItems(index) {
                if (!index) index = 1
                this.paged = true
                const params = {}
                if (this.searchKey && this.searchKey.trim() !== '') {
                    params.q = this.searchKey
                }
                axios.get(`clipboard/items/${index}`, {params})
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    // this.items = data['msg']['items'] ? data['msg']['items'] : this.items
                                    if (index === 1) {
                                        this.items.length = 0
                                    }
                                    this.items.push(...data['msg'].items)
                                    this.pageIndex = data['msg'].page.index
                                    this.pages = data['msg'].page.pages
                                    
                                    this.loadImgs(data['msg'].items.map(item=>item.id))
                                    // for (let item of data['msg'].items) {
                                    //     this.loadImg(item.id)
                                    // }
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    }).finally(()=>{
                        this.paged = false
                    })
            },
            loadItemsAll() {
                axios.get('clipboard/items')
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    this.items = data['msg']['items'] ? data['msg']['items'] : this.items
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            loadImgs(ids) {
                let params = { ids }
                axios.get('clipboard/datas', params)
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    data['msg'].items.forEach(item => {
                                        const target = this.items.find(i => i.id === item.id)
                                        if (target) {
                                            target.type = item.type
                                            target.content = item.content
                                        }
                                    })
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            loadImg(id) {
                let params = { id }
                axios.get('clipboard/datas', params)
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    data['msg'].items.forEach(item => {
                                        const target = this.items.find(i => i.id === item.id)
                                        target.type = item.type
                                        target.content = item.content
                                    })
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            onPaste(event) {
                event.target.value = ''
                let text = event.target.value
                // let clipped = event.clipboardData.getData('text')
                // log(clipped, 1)
                let items = event.clipboardData.items
                if (items) {
                    let data = []
                    function loadClip() {
                        for (let i = 0, l = items.length; i < l; ++i) {
                            let item = items[i]
                            // console.log(item, i)
                            let kind = item.kind
                            let type = item.type
                            if (item.kind === 'string') {
                                item.getAsString((val) => { data.push({ 'kind': kind, 'type': type, 'text': val }) })
                                // console.log(item, 2121)
                            }
                            if (item.kind === 'file') {
                                let blod = item.getAsFile()
                                let name = blod.name
                                let size = blod.size
                                let type = blod.type
                                const reader = new FileReader();
                                reader.onload = function (event) {
                                    // event.target.result 即为图片的Base64编码字符串
                                    let base64_str = event.target.result
                                    data.push({ 'kind': kind, 'type': type, name: name, size: size, 'text': base64_str })
                                }
                                reader.readAsDataURL(item.getAsFile());
                            }
                        }
                    }
                    loadClip()
                    this.loading = true
                    setTimeout(() => {
                        text = event.target.value
                        let params = { data: data, text: text }
                        // console.log(params)
                        post('clipboard', params, {
                            _success: (data) => { this.loadItems() },
                            _error: (data) => { console.log(data) },
                            _final: () => { this.loading = false }
                        })
                    }, 3000)

                } else {
                    let clipped = event.clipboardData.getData('text')
                    log(clipped, 1)
                }
            },
            deleteItem(item) {
                console.log('delete: ' + JSON.stringify(item))
                let content = '...'
                if (item.content) {
                    content = item.content.substr(0, 15)
                }
                if (confirm(" 是否删除[" + content + "...] ")) {
                    axios.get('clipboard/delete/' + item.id)
                        .then(
                            response => {
                                // console.log(response);
                                if (response.status === 200) {
                                    let data = response.data
                                    if (data['code'] === 0) {
                                        console.log('SUCCESS: ' + data['msg'])
                                        this.loadItems()
                                    } else {
                                        console.log('FAILED: ' + data['msg'])
                                    }
                                }
                            })
                        .catch(function (error) {
                            console.log(error);
                        });
                }
            },
            viewdoc(item) {
                let params = { 'id': item['id'], 'kind': 'string' }
                get('clipboard/data', params, {
                    _success: (data) => {
                        if (data['code'] === 0 && data['msg']['items'].length > 0) {
                            let item = data['msg']['items'][0]
                            let text = item['text']
                            this.vue_clipview.show = true
                            document.querySelector('.clipview').innerHTML = ''
                            const txt = document.createElement('textarea')
                            // style="height: 100%;width: 100%;resize:none;"
                            txt.style.width = '100%'
                            txt.style.height = '75vh'
                            txt.style.resize = 'none'
                            txt.readOnly = true
                            txt.value = text
                            // document.querySelector('.clipview').innerHTML = text
                            document.querySelector('.clipview').appendChild(txt)
                            // console.log(text)
                        }
                    },
                    _error: (data) => { console.log(data) }
                })
            },
            viewimg(item) {
                let params = { 'id': item['id'], 'kind': 'file' }
                get('clipboard/data', params, {
                    _success: (data) => {
                        if (data['code'] === 0 && data['msg']['items'].length > 0) {
                            let item = data['msg']['items'][0]
                            if (item['type'].startsWith('image')) {
                                let text = item['content']
                                this.vue_clipview.show = true
                                let img = document.createElement('img')
                                img.style.width = '100%'
                                img.src = text
                                document.querySelector('.clipview').innerHTML = ''
                                document.querySelector('.clipview').appendChild(img)
                                // console.log(text)
                            }
                        }
                    },
                    _error: (data) => { console.log(data) }
                })
            },
            copyContent(e) {
                let el = e.target
                el.select()
                document.execCommand('Copy')
                console.log('复制: \n' + el.value)
            },
            exportAll() {
                axios.get('clipboard/export')
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    // this.items = data['msg']['items'] ? data['msg']['items'] : this.items
                                    this.vue_export.content = JSON.stringify(data['msg']['items'], null, "\t")
                                    this.vue_export.show = true
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
                // console.log(JSON.stringify(this.items, null, "\t"))
                // this.vue_export.content = JSON.stringify(this.items, null, "\t")
                // this.vue_export.show = true
            },
            exportOne(item) {
                axios.get('clipboard/export/' + item.id)
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    // this.items = data['msg']['items'] ? data['msg']['items'] : this.items
                                    this.vue_export.content = JSON.stringify(data['msg']['items'], null, "\t")
                                    this.vue_export.show = true
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
                // console.log(JSON.stringify(this.items, null, "\t"))
                // this.vue_export.content = JSON.stringify(this.items, null, "\t")
                // this.vue_export.show = true
            },
            importClip() {
                this.vue_import.show = true
            },
            onImportClip(content) {
                let objs = []
                try {
                    objs = JSON.parse(content)
                } catch (error) {
                    alert(error.message)
                    return
                }
                if (!(objs instanceof Array)) return
                objs.reverse()
                let items = []
                objs.forEach(el => {
                    if (el['content'] && el['content'].length > 0) {
                        items.push({ content: el['content'], data: el['data'] })
                    }
                });
                if (items.length <= 0) {
                    alert("items is empty")
                    return
                }
                axios.post('clipboard/import', {
                    items: items
                })
                    .then(
                        response => {
                            // console.log(response);
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    console.log('SUCCESS: ' + data['msg'])
                                    this.loadItems()
                                    this.vue_import.show = false
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
        },
        computed: {
        }
    }
    const app = Vue.createApp(clipboard)
    // mount方法返回根组件实例
    const vm = app.mount('#main')
</script>
{% endblock %}